import React, { useContext, useEffect, useRef, useState } from 'react';
import { DeleteOutlined, EditOutlined, FolderOutlined, SettingOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse, Select, Drawer, Button, Input, Checkbox, Tree, Modal } from 'antd';
import { CloudUploadOutlined, FolderAddOutlined, EnvironmentOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Platte, Aiming, DeleteOne } from '@icon-park/react';
import EmptyLayerGroup from './EmptyLayerGroup';
import AddMapTopicModal from '../modal/AddMapTopicModal';
import UploadShpFileModal from '../modal/UploadShpFileModal';
import SmartMapContext from '../provider/SmartMapProvider'
import { addTreePropertyForList, commonErrorMsg, commonSuccessMsg, generateTreeData, isEmpty, makeClassNameList, toastShort, tree2List } from '../utils';
import { MapTopic } from '../typings';


const SmartMapLayerManage = () => {

    const {
        tdt_map_token,
        mapbox_token,
        mapMountingRootId,
        uploadActionUrl,
        pageParamsTag,
        defaultMapLayerPid,
        addMapLayerPromiseFunc,
        editMapLayerPromiseFunc,
        deleteMapLayerPromiseFunc,
        queryMapLayerPromiseFunc,
        layerManageDrawerOpen,
        setLayerManageDrawerOpen,
        checkedThirdPartyLayerList,
        handleSetCheckedThirdPartyLayerList
    } = useContext(SmartMapContext);

    const addMapTopicModalRef = useRef(null);
    const uploadShpFileModalRef = useRef(null);

    const [isDrawerOpen, setIsDrawerOpen] = useState(true);
    const [deleteLoading, setDeleteLoading] = useState(false);
    const tempDeleteMapLayer = useRef<MapTopic>(null);

    useEffect(() => {
        queryMapTopicAndLayerList();
    }, [])

    const [treeData, setTreeData] = useState<MapTopic[]>([])

    const handleOpenAddMapTopicModal = () => {
        addMapTopicModalRef.current.openModal();
    }

    const handleOpenUploadShpFileModal = () => {
        uploadShpFileModalRef.current.openModal();
    }

    const queryMapTopicAndLayerList = () => {
        let params = {
            size: 9999,
            page: 1,
        };
        if (pageParamsTag == 'pageIndex') {
            //@ts-ignore
            params.pageNum = 1;
            //@ts-ignore
            params.pageSize = 9999
        }
        if (!isEmpty(defaultMapLayerPid)) {
            //@ts-ignore
            params.pid = defaultMapLayerPid;
        }
        queryMapLayerPromiseFunc(params)
            .then(res => {
                console.log("queryMapLayerPromiseFunc--->", res)
                const mapTopicList = res.data.list;
                const mapTopicTree: MapTopic[] = generateTreeData(addTreePropertyForList(mapTopicList));
                console.log("mapTopicTree--->", mapTopicTree)
                //@ts-ignore
                setTreeData(mapTopicTree)
            })
            .catch(err => {
                console.log("queryMapLayerPromiseFunc--->err")
            })
    }

    const _onFinish = () => {
        toastShort('success', commonSuccessMsg);
        queryMapTopicAndLayerList();
    }

    const adaptMapLayerIcon = (node: MapTopic) => {
        switch (node.layerType) {
            case 'shape':
                return require('./../assets/shape.png');
                break;
            case 'line':
                return require('./../assets/line.png');
                break;
            case 'symbol':
                return require('./../assets/symbol.png');
                break;
            default:
                return null;
                break;
        }
    }

    const stopPropagation = (e: any) => {
        e.stopPropagation();
    }

    const handleEditMapLayer = (mapLayer: MapTopic) => {
        if (mapLayer.layerType == 'topic') {
            addMapTopicModalRef.current.openModal(mapLayer);
        } else {
            uploadShpFileModalRef.current.openModal(mapLayer);
        }
    }

    const [modal, contextHolder] = Modal.useModal();

    const handleDeleteMapLayer = (mapLayer: MapTopic) => {
        tempDeleteMapLayer.current = mapLayer;
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除此地图数据？此操作不可撤销',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: confirmToDeleteMapLayer,
            okButtonProps: { loading: deleteLoading }
        });
    }

    const confirmToDeleteMapLayer = () => {
        let params = {
            ids: tempDeleteMapLayer.current.id
        }
        setDeleteLoading(true);
        deleteMapLayerPromiseFunc(params)
            .then(res => {
                _onFinish();
                setDeleteLoading(false);
            })
            .catch(err => {
                toastShort('error', commonErrorMsg)
                setDeleteLoading(false);
            })
    }


    const renderMapTreeNode = (node: MapTopic) => {
        return (
            <div
                className='custom-tree-node'
                key={node.id}
            // onContextMenu={(e) => onNodeContextMenu(e, node)}
            >
                <div
                    style={{
                        width: node.layerType == 'topic' ? 204 : 180
                    }}
                    className='flex-row topic-tree-node'
                >
                    <div className='flex-row topic-tree-node-left'>
                        {
                            node.layerType !== 'topic' ?
                                <img
                                    src={adaptMapLayerIcon(node)}
                                    className='topic-tree-node-layer-icon'
                                />
                                :
                                <FolderOutlined style={{ marginRight: 3 }} />
                        }
                        <div className='single-line-text' style={{ width: 112 }}>{node.title}</div>
                    </div>
                    <div
                        className='flex-row topic-tree-node-right'
                        onClick={stopPropagation}
                        onMouseDown={stopPropagation}
                        onMouseUp={stopPropagation}
                    >
                        <Button
                            size={'small'}
                            icon={<EditOutlined />}
                            type={'text'}
                            onClick={() => handleEditMapLayer(node)}
                        />
                        <Button
                            size={'small'}
                            icon={<DeleteOutlined />}
                            type={'text'}
                            danger
                            onClick={() => handleDeleteMapLayer(node)}
                        />
                    </div>
                </div>
            </div>
        );
    }

    const onMapLayerCheckedChange = (checkedMapLayerKeyList: string[]) => {
        console.log("checkedMapLayerKeyList---->", checkedMapLayerKeyList);
        const currentCheckedMapLayerList = [];
        const mapTopciList: MapTopic[] = tree2List(treeData);
        mapTopciList.forEach(mapTopic => {
            if (
                checkedMapLayerKeyList.includes(mapTopic.id) &&
                mapTopic.layerType !== 'topic'
            ) {
                currentCheckedMapLayerList.push(mapTopic);
            }
        })
        console.log("currentCheckedMapLayerList--->", currentCheckedMapLayerList)
        handleSetCheckedThirdPartyLayerList(currentCheckedMapLayerList);
    }

    return (
        <div
            className={
                makeClassNameList([
                    'flex-col smart-map-layer-list',
                    layerManageDrawerOpen ? 'show' : 'hide'
                ])
            }
        >
            <div className='flex-row smart-map-layer-list-search'>
                <Input.Search
                    placeholder={"搜索专题或图层名称"}
                    style={{ width: 258 }}
                />
            </div>
            <div className='flex-row smart-map-layer-list-header'>
                <Button
                    icon={<FolderAddOutlined />}
                    onClick={handleOpenAddMapTopicModal}
                >
                    新建地理专题
                </Button>
                <Button
                    icon={<CloudUploadOutlined />}
                    type={'primary'}
                    onClick={handleOpenUploadShpFileModal}
                >
                    导入图层
                </Button>
            </div>
            <div className='smart-map-layer-list-content'>
                <Tree
                    treeData={treeData}
                    showLine
                    checkable
                    titleRender={renderMapTreeNode}
                    selectable={false}
                    onCheck={onMapLayerCheckedChange}
                />
            </div>
            {contextHolder}
            <AddMapTopicModal
                ref={addMapTopicModalRef}
                onFinish={_onFinish}
            />
            <UploadShpFileModal
                ref={uploadShpFileModalRef}
                onFinish={_onFinish}
            />
        </div>
    )
}

export default SmartMapLayerManage;